<?php
/**
 * Skyline :: Patterns & component framework
 * Copyright 2010-2011 Ian Unruh (Xerof3ar)
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
namespace Skyline\Structure\Set;
use ArrayIterator;

/**
 * 
 * 
 * @author Ian Unruh (Xerof3ar) <ianunruh@gmail.com>
 * @since Class avaliable since release 1.0
 */
class SimpleSet extends AbstractSet
{
	/**
	 * @var bool
	 */
	protected $changed = false;
	
	/**
	 * @var mixed[]
	 */
	protected $elements = array();
	
	/**
	 * Add an element to the collection
	 * 
	 * @param mixed $element
	 * @return void
	 */
	public function add($element)
	{
		$this->assertNotFull();
		$this->assertElementIsValid($element);
		if($this->contains($element)) {
			return false;
		}
		$this->elements[] = $element;
		$this->changed = true;
		return true;
	}
	
	/**
	 * Clears this container of all its elements
	 * @return void
	 */
	public function clear()
	{
		$this->elements = array();
	}
	
	/**
	 * Returns true if an element exists in the collection
	 * 
	 * @param mixed $element
	 * @return bool
	 */
	public function contains($element)
	{
		foreach($this->elements as $e) {
			if($e === $element) {
				return true;
			}
		}
		return false;
	}
	
	/**
	 * Removes an element from the collection
	 * 
	 * @param mixed $element
	 * @return void
	 */
	public function remove($element)
	{
		foreach($this->elements as $offset => $e) {
			if($e === $element) {
				unset($this->elements[$offset]);
				$this->changed = true;
				return;
			}
		}
	}
	
	/**
	 * Returns this collection as a simple PHP array
	 * @return mixed[]
	 */
	public function toArray()
	{
		if($this->changed && !is_null($this->comparator)) {
			usort($this->elements, array($this->comparator, 'compare'));
		}
		return array_values($this->elements);
	}
	
	/**
	 * Returns the number of elements in this set
	 * @return int
	 */
	public function count()
	{
		return count($this->elements);
	}
	
	/**
	 * Returns an iterator for the elements in this set
	 * @return Iterator
	 */
	public function getIterator()
	{
		return new ArrayIterator($this->toArray());
	}
}